package com.dongchedi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dongchedi.entity.*;
import com.dongchedi.mapper.*;
import com.dongchedi.service.OrderService;
import com.dongchedi.utils.HostHolder;
import com.dongchedi.utils.OrderEncodingUtil;
import com.dongchedi.utils.constant.ColorConstant;
import com.dongchedi.utils.constant.RedisConstantKey;
import com.dongchedi.utils.page.PageRequest;
import com.dongchedi.utils.page.PageResult;
import com.dongchedi.utils.page.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author leibidong
 * @description订单实现类
 * @date 2021/6/26
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMasterMapper orderMasterMapper;
    @Autowired
    ProductPicInfoMapper productPicInfoMapper;
    @Autowired
    ProductInfoMapper productInfoMapper;
    @Autowired
    CustomerAddrMapper customerAddrMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @Resource
    HostHolder hostHolder;
    /*
     * @Author: leibidong
     * @Description: 根据订单状态分类查询主订单
     * @Date: 2021/6/26 19:59
     * @Param: [customerId, orderStatus, pageNum, pageSize]
     * @Return: com.alibaba.fastjson.JSONArray
     **/
    @Override
    public JSONArray searchOrderByStatus(Integer customerId,Integer orderStatus,Integer pageNum,Integer pageSize) {
        JSONArray jsonArray = new JSONArray();
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerId.equals(customerLogin.getId())) {
            PageHelper.startPage(pageNum, pageSize);
            PageRequest pageRequest = new PageRequest(pageNum, pageSize);
            List<OrderMaster> list = orderMasterMapper.queryOrderByStatus(customerId, orderStatus);
            PageResult pageResult = PageUtil.getPageResult(pageRequest, new PageInfo<OrderMaster>(list));
            for (int i = 0; i < pageResult.getContent().size(); i++) {
                OrderMaster orderMaster = (OrderMaster) pageResult.getContent().get(i);
                JSONObject node = new JSONObject();
                ProductPicInfo list1 = productPicInfoMapper.queryByProductId(orderMaster.getProductId());
                node.put("id", orderMaster.getId());
                node.put("customerId", orderMaster.getCustomerId());
                node.put("productId", orderMaster.getProductId());
                node.put("productEncoding", orderMaster.getProductEconding());
                node.put("productName", orderMaster.getProductName());
                node.put("districtPrice", orderMaster.getDistrictPrice());
                node.put("colorType", ColorConstant.HEIHUI.getNameByIndex(orderMaster.getColorType()));
                node.put("productCnt", orderMaster.getProductCnt());
                node.put("orderStatus", orderMaster.getOrderStatus());
                node.put("picUrl", list1.getPicUrl());
                jsonArray.add(node);
            }
            return jsonArray;
        }else {
            return  jsonArray;
        }
    }
    /*
     * @Author: leibidong
     * @Description: 添加订单
     * @Date: 2021/6/26 20:00
     * @Param: [customerId, productId, type, orderAmount]
     * @Return: com.alibaba.fastjson.JSONObject
     **/
    @Override
    public JSONObject addOrder(Integer customerId, Integer productId, String type, Integer orderAmount,
                               Integer addressId) {
        JSONObject jsonObject=new JSONObject();
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerId.equals(customerLogin.getId())) {
            ProductInfo productInfo = productInfoMapper.queryById(productId, customerId);
            CustomerAddr customerAddr = customerAddrMapper.selectAddressByAddressId(addressId);
            if (productInfo != null && customerAddr != null) {
                OrderMaster orderMaster = new OrderMaster();
                orderMaster.setProductEconding(productInfo.getEncoding());
                orderMaster.setProductName(productInfo.getName());
                orderMaster.setColorType(ColorConstant.HEIHUI.getIndexByName(type));
                orderMaster.setCustomerId(customerId);
                orderMaster.setProductId(productId);
                orderMaster.setCustomerName(customerAddr.getCustomerName());
                orderMaster.setPrice(productInfo.getPrice());
                orderMaster.setDistrictPrice(productInfo.getAverageCost());
                orderMaster.setProductCnt(orderAmount);
                BigDecimal b = new BigDecimal(Integer.parseInt(orderAmount.toString()));
                BigDecimal b1 = b.multiply(productInfo.getAverageCost());
                orderMaster.setPaymentMoney(b1);
                orderMaster.setAddress(customerAddr.getAddress());
                Date date = new Date();
                Timestamp nousedate = new Timestamp(date.getTime());
                orderMaster.setCreateTime(nousedate);
                orderMaster.setModifiedTime(nousedate);
                orderMaster.setOrderStatus(1);
                Integer i = orderMasterMapper.insertMasterOrder(orderMaster);
                if (i != 0) {
                    jsonObject.put("id", orderMaster.getId());
                }
            }
            return jsonObject;
        }else {
            return jsonObject;
        }
    }
    /*
     * @Author: leibidong
     * @Description: 根据主订单id查询出详细订单内容
     * @Date: 2021/6/26 20:00
     * @Param: [customerId, orderId]
     * @Return: com.alibaba.fastjson.JSONObject
     **/
    @Override
    public JSONObject selectOrderDetail(Integer customerId, Integer orderId) {
        JSONObject jsonObject=new JSONObject();
        CustomerLogin customerLogin=hostHolder.getUser();
        if(customerId.equals(customerLogin.getId())) {
            OrderDetail orderDetail1 = orderDetailMapper.queryByOrderId(customerId,orderId);
            if (orderDetail1 == null) {
                OrderMaster orderMaster = orderMasterMapper.queryByorderId(orderId);
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setProductEconding(orderMaster.getProductEconding());
                orderDetail.setProductId(orderMaster.getProductId());
                orderDetail.setCustomerId(customerId);
                orderDetail.setProductName(orderMaster.getProductName());
                orderDetail.setEconding(OrderEncodingUtil.getOrderCode(customerId));
                orderDetail.setProductCnt(orderMaster.getProductCnt());
                orderDetail.setProductPrice(orderMaster.getPrice());
                orderDetail.setDistrictPrice(orderMaster.getDistrictPrice());
                BigDecimal b = new BigDecimal(Integer.parseInt(orderMaster.getProductCnt().toString()));
                BigDecimal b1 = b.multiply(orderMaster.getDistrictPrice());
                orderDetail.setTotalMoney(b1);
                BigDecimal b2 = new BigDecimal(100);
                orderDetail.setLogisticsMoney(b2);
                orderDetail.setRealityMoney(b2.add(b1));
                orderDetail.setColorType(orderMaster.getColorType());
                orderDetail.setOrderStatus(orderMaster.getOrderStatus());
                Date date = new Date();
                Timestamp nousedate = new Timestamp(date.getTime());
                orderDetail.setCreateTime(nousedate);
                orderDetailMapper.insertByOrderMaster(orderDetail);
                if (orderDetail.getId() != 0 || orderDetail.getId() != null) {
                    Integer mainProductId = productInfoMapper.searchMainProductId(customerId, orderDetail.getProductId());
                    List<ProductPicInfo> productPicInfo = productPicInfoMapper.queryById(mainProductId);
                    if (productPicInfo.size() != 0) {
                        OrderMaster o=orderMasterMapper.queryAddressByid(orderId);
                        CustomerAddr customerAddr=customerAddrMapper.selectPhoneByNameAddress(o.getCustomerName(),
                                o.getAddress());
                        jsonObject.put("phone",customerAddr.getCustomerPhone());
                        jsonObject.put("customerName",o.getCustomerName());
                        jsonObject.put("address",o.getAddress());
                        jsonObject.put("id", orderDetail.getId());
                        jsonObject.put("Econding", orderDetail.getEconding());
                        jsonObject.put("productId", orderDetail.getProductId());
                        jsonObject.put("customerId", orderDetail.getCustomerId());
                        jsonObject.put("productEncoding", orderDetail.getProductEconding());
                        jsonObject.put("productName", orderDetail.getProductName());
                        jsonObject.put("productCnt", orderDetail.getProductCnt());
                        jsonObject.put("productPrice", orderDetail.getProductPrice());
                        jsonObject.put("districtPrice", orderDetail.getDistrictPrice());
                        jsonObject.put("totalMoney", orderDetail.getTotalMoney());
                        jsonObject.put("logisticsMoney", orderDetail.getLogisticsMoney());
                        jsonObject.put("realityMoney", orderDetail.getRealityMoney());
                        jsonObject.put("colorType", ColorConstant.HEIHUI.getNameByIndex(orderDetail.getColorType()));
                        jsonObject.put("orderStatus", orderDetail.getOrderStatus());
                        jsonObject.put("createTime", orderDetail.getCreateTime());
                        jsonObject.put("productPicUrl", productPicInfo.get(0).getPicUrl());
                        String key = RedisConstantKey.getOrderdetail(customerId, orderDetail.getOrderId());
                        redisTemplate.opsForValue().set(key, jsonObject.toJSONString(), 3600, TimeUnit.SECONDS);
                        return jsonObject;
                    } else {
                        return jsonObject;
                    }
                } else {
                    return jsonObject;
                }
            } else {
                String key = RedisConstantKey.getOrderdetail(customerId, orderId);
                String t = (String) redisTemplate.opsForValue().get(key);
                if (t != null) {
                    return JSON.parseObject(t);
                } else {
                    OrderDetail orderDetail = orderDetailMapper.selectByOrderId(customerId, orderId);
                    if (orderDetail != null) {
                        Integer mainProductId = productInfoMapper.searchMainProductId(customerId, orderDetail.getProductId());
                        List<ProductPicInfo> productPicInfo = productPicInfoMapper.queryById(mainProductId);
                        if (productPicInfo.size() != 0) {
                            OrderMaster o=orderMasterMapper.queryAddressByid(orderId);
                            CustomerAddr customerAddr=customerAddrMapper.selectPhoneByNameAddress(o.getCustomerName(),
                                    o.getAddress());
                            jsonObject.put("phone",customerAddr.getCustomerPhone());
                            jsonObject.put("customerName",o.getCustomerName());
                            jsonObject.put("address",o.getAddress());
                            jsonObject.put("id", orderDetail.getId());
                            jsonObject.put("econding", orderDetail.getEconding());
                            jsonObject.put("productId", orderDetail.getProductId());
                            jsonObject.put("customerId", orderDetail.getCustomerId());
                            jsonObject.put("productEncoding", orderDetail.getProductEconding());
                            jsonObject.put("productName", orderDetail.getProductName());
                            jsonObject.put("productCnt", orderDetail.getProductCnt());
                            jsonObject.put("productPrice", orderDetail.getProductPrice());
                            jsonObject.put("districtPrice", orderDetail.getDistrictPrice());
                            jsonObject.put("totalMoney", orderDetail.getTotalMoney());
                            jsonObject.put("logisticsMoney", orderDetail.getLogisticsMoney());
                            jsonObject.put("realityMoney", orderDetail.getRealityMoney());
                            jsonObject.put("colorType", ColorConstant.HEIHUI.getNameByIndex(orderDetail.getColorType()));
                            jsonObject.put("orderStatus", orderDetail.getOrderStatus());
                            jsonObject.put("createTime", orderDetail.getCreateTime());
                            jsonObject.put("productPicUrl", productPicInfo.get(0).getPicUrl());
                            redisTemplate.opsForValue().set(key, jsonObject.toJSONString(), 3600, TimeUnit.SECONDS);
                            return jsonObject;
                        } else {
                            return jsonObject;
                        }
                    }
                }
            }
            return jsonObject;
        }else {
            return jsonObject;
        }
    }
    /*
     * @Author: leibidong
     * @Description: 商品结账
     * @Date: 2021/6/26 20:00
     * @Param: [customerId, orderDetailId]
     * @Return: com.alibaba.fastjson.JSONObject
     **/
   @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public JSONObject appayOrder(Integer customerId, Integer orderDetailId) {
       CustomerLogin customerLogin=hostHolder.getUser();
       JSONObject jsonObject = new JSONObject();
       if(customerId.equals(customerLogin.getId())) {
           OrderDetail orderDetail = orderDetailMapper.queryByOrderDetailId(customerId, orderDetailId);

           int status = orderMasterMapper.queryStatus(customerId, orderDetail.getOrderId());
           if (orderDetail != null && orderDetail.getOrderStatus() == 1 && status == 1) {
               Date date = new Date();
               Timestamp payTime = new Timestamp(date.getTime());
               Integer i = orderDetailMapper.updateOrderStatus(customerId, orderDetailId, payTime);
               Integer i1 = orderMasterMapper.updateOrderStatus(customerId, orderDetail.getOrderId(), payTime);
               if (i != 0 && i1 != 0) {
                   jsonObject.put("status", "ok");
               }
           }
           return jsonObject;
       }else {
           return   jsonObject;
       }
    }
}
